package cc.admin.modules.sys.controller;

import cc.admin.common.api.vo.Result;
import cc.admin.common.constant.WeChatConstant;
import cc.admin.common.constant.WeChatTemplateConstant;
import cc.admin.modules.sys.util.WeChatUtil;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * The type We chat controller.
 */
@Slf4j
@RestController
@RequestMapping("/weChat")
public class WeChatController {


    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 微信验证token
     *
     * @param request  the request
     * @param response the response
     * @return string boolean
     */
    @GetMapping("/checkToken")
    public void checkToken(HttpServletRequest request, HttpServletResponse response) {
        try {
            // 微信加密签名
            String signature = request.getParameter("signature");
            // 随机字符串
            String echostr = request.getParameter("echostr");
            // 时间戳
            String timestamp = request.getParameter("timestamp");
            // 随机数
            String nonce = request.getParameter("nonce");

            response.setContentType("application/json;charset=UTF-8");
            response.setCharacterEncoding("UTF-8");

            //排序
            String[] arr = {WeChatConstant.TOKEN, timestamp, nonce};
            Arrays.sort(arr);
            StringBuilder content = new StringBuilder();
            for (int i = 0; i < arr.length; i++) {
                content.append(arr[i]);
            }

            //sha1Hex 加密
            MessageDigest md = null;
            String temp = null;
            try {
                md = MessageDigest.getInstance("SHA-1");
                byte[] digest = md.digest(content.toString().getBytes());
                temp = byteToStr(digest);
                log.info("加密后的token:" + temp);
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            }
            if (temp.toLowerCase().equals(signature)) {
                response.getWriter().write(echostr);
            }
        } catch (Exception e) {
            e.printStackTrace();
            //相应的处理
        }
    }


    private static String byteToStr(byte[] byteArray) {
        String strDigest = "";
        for (int i = 0; i < byteArray.length; i++) {
            strDigest += byteToHexStr(byteArray[i]);
        }
        return strDigest;
    }

    private static String byteToHexStr(byte mByte) {
        char[] Digit = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
        char[] tempArr = new char[2];
        tempArr[0] = Digit[(mByte >>> 4) & 0X0F];
        tempArr[1] = Digit[mByte & 0X0F];
        String s = new String(tempArr);
        return s;
    }


    // 获取微信用户信息
    @RequestMapping(value = "/getUserInfo", method = RequestMethod.GET)
    public JSONObject getWxUserInfo(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 获取code
        String code = request.getParameter("code");
        // 获取access_token
        String url = WeChatConstant.ACCESS_USER_TOKEN_URL + "&code=" + code + "&grant_type=authorization_code";
        JSONObject jsonObject = JSONObject.parseObject(WeChatUtil.httpRequest(url, "GET", null));
        String openid = jsonObject.getString("openid");
        String access_token = jsonObject.getString("access_token");
        // 获取用户信息
        String userUrl = WeChatConstant.USER_INFO_URL + "?access_token=" + access_token + "&openid=" + openid + "&lang=zh_CN";
        JSONObject userInfo = JSONObject.parseObject(WeChatUtil.httpRequest(userUrl, "GET", null));
        return userInfo;
    }


    /**
     * 用户openid绑定手机号
     * @param openid
     * @param phone
     * @return
     */
    @PostMapping("/bindPhone")
    public Result<?> bindPhone(@RequestParam String openid, @RequestParam String phone){
        try {
            jdbcTemplate.update("INSERT INTO wx_gzh_user (`id`, `openid`, `phone`, `create_time`, `update_time`) VALUES (?, ?, ?, ?, NULL)", IdUtil.randomUUID(), openid, phone, new Date());
            return Result.ok("绑定成功！");
        }catch (Exception e){
            return Result.error(e.getMessage());
        }
    }

    /**
     * 根据用户的openid查询手机号
     * @param openid
     * @return
     */
    @GetMapping("/userPhone")
    public Result<?> userPhone(@RequestParam  String openid){
        List<Map<String, Object>> users = jdbcTemplate.queryForList("select phone from wx_gzh_user where openid=?", openid);
        if(!users.isEmpty()){
            return Result.ok(users.get(0).get("phone"));
        }else{
            return Result.error("请绑定手机号！");
        }
    }



	@Autowired
	private KafkaTemplate<String, Object> kafkaTemplate;

	/**
	 * 测试发送消息
	 * @return
	 */
	@GetMapping("/test")
	public Result<?> test(){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String ctime = sdf.format(new Date());
		// 构造模板消息参数
		JSONObject data = new JSONObject();
		JSONObject name = new JSONObject();
		//姓名
		name.put("value", "测试用户");
		data.put("thing28", name);
		//触发时间
		JSONObject cftime = new JSONObject();
		cftime.put("value", ctime);
		data.put("time22", cftime);
		//工单名称
		JSONObject gdmc = new JSONObject();
		gdmc.put("value", "测试发送标题");
		data.put("thing8", gdmc);
		JSONObject ct = new JSONObject();
		//触发内容
		ct.put("value", "张厚营的出海证，更换日期已逾期1天");
		data.put("thing4", ct);
		System.out.println("微信数组组装" + data);

		String phone = "15811270105";
		JSONObject msg = new JSONObject();
		msg.put("phone", phone);
		msg.put("templateId", WeChatTemplateConstant.GDRW_TEMPLATEID);
		msg.put("data", data);
		log.info("给用户:{},推送消息:{}",phone,data.toJSONString());
		kafkaTemplate.send("topic.wei.xin", msg.toJSONString());
		return Result.ok();
	}


}
